package com.yhq.basic.algorithm.array;

import java.util.LinkedHashMap;

/**
 * @author hqyin
 * @date 2023/8/24 3:36 下午
 */
public class MyLRUCache<K,V> {
    private int size;
    private LinkedHashMap<K,V> cache;


    public MyLRUCache(int size) {
        if(size <= 0) {
            throw new RuntimeException("容量必须是正整数，size="+size);
        }
        this.size = size;
        cache = new LinkedHashMap<>();
    }

    public V get(K key) {
        if(!cache.containsKey(key)) {
            return null;
        }
        V value = cache.remove(key);
        cache.put(key,value);
        return value;
    }

    public void put(K key,V value) {
        if(cache.containsKey(key)) {
            cache.put(key,value);
        } else if(cache.size() == size) {
            cache.remove(cache.keySet().iterator().next());
            cache.put(key,value);
        } else {
            cache.put(key,value);
        }
    }

    @Override
    public String toString() {
        return cache.toString();
    }
}
